package routes

import (
	"html/template"
	"myblog/configs"
	"myblog/controllers"
	"myblog/middleware"
	"myblog/models"
	"myblog/repositories"
	"myblog/services"
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func SetupRouter() *gin.Engine {
	r := gin.Default()

	// 设置自定义模板函数
	r.SetFuncMap(template.FuncMap{
		"safeHTML": func(html string) template.HTML {
			return template.HTML(html)
		},
		"now": func() int {
			return time.Now().Year()
		},
	})

	// 加载模板
	r.LoadHTMLGlob(filepath.Join(os.Getenv("PWD"), "templates/**/*"))
	// r.LoadHTMLGlob("templates/**/*")


	// 静态文件
	r.Static("/static", "./static")

	// 加载配置
	cfg := configs.LoadConfig()

	// 初始化数据库
	db, err := gorm.Open(mysql.Open(cfg.Database.DSN), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败: " + err.Error())
	}

	// 自动迁移模型
	db.AutoMigrate(&models.Article{})

	// 初始化依赖
	articleRepo := repositories.NewArticleRepository(db)
	articleService := services.NewArticleService(articleRepo)
	articleController := controllers.NewArticleController(articleService)
	adminController := controllers.NewAdminController(articleService, cfg)

	// 前端路由
	r.GET("/", articleController.HomePage)
	r.GET("/article/:slug", articleController.ArticleDetail)

	// 后台路由组
	admin := r.Group("/admin")
	{
		admin.GET("/login", adminController.LoginPage)
		admin.POST("/login", adminController.Login)
		admin.GET("/logout", adminController.Logout)

		// 需要认证的路由
		authGroup := admin.Group("")
		authGroup.Use(middleware.AuthMiddleware(cfg)) // 使用中间件
		{
			authGroup.GET("/articles", adminController.ArticleList)
			authGroup.GET("/article/new", adminController.EditArticlePage)
			authGroup.GET("/article/:id", adminController.EditArticlePage)
			authGroup.POST("/article/save", adminController.SaveArticle)
			authGroup.GET("/article/delete/:id", adminController.DeleteArticle)
		}
	}

	return r
}
